package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/microcosm-cc/bluemonday"
	"github.com/russross/blackfriday"
	"io/ioutil"
	"os"
	"softwareEngineering/models"
	"softwareEngineering/tools"
	"strconv"
)

var FileUploadSql = func(user models.User, title string, path string) {
	o := orm.NewOrm()
	article := models.Article{}
	article.Uid = user.Id
	article.Title = title
	article.Content = readFile(path)
	article.Path = path

	_, err := o.Insert(&article)
	if err != nil {
		beego.Info("上传成功")
	}
}

var ImageUploadSql = func(user models.User, name string, path string) {
	o := orm.NewOrm()
	image := models.Image{}
	image.Uid = user.Id
	image.Name = name
	image.Path = path

	_, err := o.Insert(&image)
	if err != nil {
		beego.Info("上传图片成功")
	}

}

func QueryAllArticle(user models.User) (ats []models.Article) {
	o := orm.NewOrm()
	articles := []models.Article{}
	qs := o.QueryTable("article")
	n, err := qs.Filter("Uid", user.Id).All(&articles)
	if err == nil && n > 0 {
		return articles
	}
	return
}

func QueryArticleById(id int) (article models.Article) {
	o := orm.NewOrm()
	art := models.Article{}
	qs := o.QueryTable("article")
	n, err := qs.Filter("id", id).All(&art)
	if err == nil && n > 0 {
		return art
	}
	return

}

func readFile(path string) (ct string) {
	f, err := os.Open(path)
	if err != nil {
		return
	}

	b, erro := ioutil.ReadAll(f)
	if erro != nil {
		return
	}

	return string(b)
}

//针对文章的相关操作
func EditArticle() {

}

func DelArticle(id int) bool {
	o := orm.NewOrm()
	article := models.Article{}
	article.Id = id
	_, err := o.Delete(&article)
	if err != nil {
		return false
	}
	return true
}

//针对视频的相关操作

func DelVideo(id int) bool {
	o := orm.NewOrm()
	video := models.Video{}
	video.Id = id
	_, err := o.Delete(&video)
	if err != nil {
		return false
	}

	return false

}

//video operations end

func QueryAllImage(user models.User) []models.Image {
	o := orm.NewOrm()
	var images []models.Image
	is := o.QueryTable("image")
	n, err := is.Filter("Uid", user.Id).All(&images)
	if err == nil && n > 0 {
		return images
	}
	return nil
}
func QueryImageById(id string) (models.Image, bool) {
	o := orm.NewOrm()
	var images models.Image
	is := o.QueryTable("image")
	n, err := is.Filter("id", id).All(&images)
	if err == nil && n > 0 {
		return images, true
	}
	return images, false
}

//删除图片功能
func DeleImageById(id int) bool {
	o := orm.NewOrm()
	images := models.Image{}
	images.Id = id
	_, err := o.Delete(&images)
	//本地删除

	//

	if err != nil {
		return false
	}
	return true
}

func ArticleContent(ArticleId int) (string, string) {
	beego.Info(ArticleId)
	input := []byte("")
	o := orm.NewOrm()
	article := models.Article{}
	qs := o.QueryTable("article")
	beego.Info(qs.Exist())
	n, err := qs.Filter("id", ArticleId).All(&article)
	if err == nil && n > 0 {
		input = []byte(article.Content)
	} else {
		return "信息有误", "信息有误"
	}
	unsafe := blackfriday.MarkdownBasic(input)
	html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
	return string(html), string(input)
}

//查询数据库中的Book数据，并返回
func QueryBookData() []models.Book {
	var books []models.Book
	o := orm.NewOrm()
	qs := o.QueryTable("book")
	n, err := qs.Filter("deploy", "1").All(&books)
	if n > 0 && err == nil {
		return books
	}
	return nil
}

func QueryBooKPageContentById(id string) []models.Book {
	var page []models.Book
	o := orm.NewOrm()
	qs := o.QueryTable("book")
	n, err := qs.Filter("id", id).All(&page)
	if n > 0 && err == nil {
		return page
	}

	return nil

}

func UpdateInfor(id int, name string, pwd string, role string, imgId string) bool {
	o := orm.NewOrm()
	user := models.User{}
	user.Id = id
	user.Name = name
	user.Pwd = pwd
	user.Role = role
	user.ImgId = imgId

	_, err := o.Update(&user, "name", "Pwd", "imgId")
	if err == nil {
		return true
	}
	return false
}

func UploadVideo(uid int, name string, path string, poster string, ty string) bool {
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	duration, err := tools.GetMP4Duration(file)
	if err != nil {
		panic(err)
	}
	fmt.Println("mp4", duration)

	o := orm.NewOrm()
	video := models.Video{}
	video.Uid = uid
	video.Name = name
	video.Path = path
	video.Poster = poster
	video.Type = ty
	video.Duration = int(duration)
	_, err = o.Insert(&video)
	if err != nil {
		return false
	}
	return true
}

func QueryVideoByUserId(uid string) []models.Video {
	o := orm.NewOrm()
	videos := []models.Video{}

	qs := o.QueryTable("video")
	n, err := qs.Filter("uid", uid).All(&videos)
	if err == nil && n > 0 {
		return videos
	} else {
		return nil
	}
}

//Insert Subcase into database
func InsertSubcaseByName(uid string, subName string) bool {
	o := orm.NewOrm()
	var subcase = models.SubCase{}
	num, _ := strconv.Atoi(uid)
	subcase.Uid = num
	subcase.Name = subName

	_, err := o.Insert(&subcase)
	if err != nil {
		return false
	} else {
		return true
	}
}

//Insert Subcase into database by submited subcase
func InsertSubcaseBySubmited(subCase models.SubCase) bool {
	o := orm.NewOrm()
	_, err := o.Update(&subCase, "name", "abstract", "tech_prepare", "process")
	if err != nil {
		return false
	} else {
		return true
	}

}

//Insert subcase imgaid
func InsertSubcaseImgIdBySubId(sri models.SRI) bool {
	o := orm.NewOrm()
	_, err := o.Insert(&sri)
	if err != nil {
		return false

	} else {
		return true
	}

}

// query all subcase in database
func QueryAllSubcasesByUserid(uid string) []models.SubCase {
	o := orm.NewOrm()
	var cases []models.SubCase
	qs := o.QueryTable("sub_case")
	n, err := qs.Filter("uid__eq", uid).All(&cases)
	if n > 0 && err == nil {
		return cases
	} else {
		return nil
	}

}

//query subcase images in database by subcaseid
func QueryImagesBySubcaseId(subid string) []string {

	o := orm.NewOrm()
	var sris []models.SRI
	qs := o.QueryTable("s_r_i")
	n, err := qs.Filter("sub_id__eq", subid).All(&sris)
	arr := make([]string, n)
	if n > 0 && err == nil {
		for i := 0; i < len(sris); i++ {
			var image models.Image
			qsimage := o.QueryTable("image")
			qsimage.Filter("id", sris[i].ImgId).All(&image)
			arr[i] = image.Path
		}

	} else {
		return nil
	}
	return arr
}

//release subcase : change subcase "display" to 1
func UpdateSubCaseDisplay(subId int, display int) bool {
	o := orm.NewOrm()
	subcase := models.SubCase{}
	subcase.Id = subId
	if o.Read(&subcase) == nil {
		subcase.Display = display
		_, err := o.Update(&subcase, "display")
		if err != nil {
			return false

		}
		return true

	}
	return false

}

//query subcases by "display=1"
func QuerySubCasesByDisplay() []models.SubCase {
	o := orm.NewOrm()
	var subcase []models.SubCase
	qs := o.QueryTable("sub_case")
	qs.Filter("display__exact", 1).All(&subcase)

	return subcase

}
